package http

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
	"vidii/model"
)

// ParseURL 解析URL并返回其各个组件
func (o *CHttp) ParseURL(rawURL string) (*model.HttpURLComponents, error) {
	// 如果URL没有协议前缀，自动添加http://以便正确解析
	if !strings.Contains(rawURL, "://") && !strings.HasPrefix(rawURL, "//") {
		rawURL = "http://" + rawURL
	}

	u, err := url.Parse(rawURL)
	if err != nil {
		return nil, fmt.Errorf("failed to parse URL: %v", err)
	}

	// 处理类似"//example.com"这样的URL
	if u.Scheme == "" && u.Host != "" {
		u.Scheme = "http"
	}

	components := &model.HttpURLComponents{
		Scheme:   u.Scheme,
		Path:     u.Path,
		Query:    u.RawQuery,
		Fragment: u.Fragment,
		IsHTTPS:  u.Scheme == "https",
	}

	// 分离域名和端口
	host := u.Host
	if strings.Contains(host, ":") {
		parts := strings.Split(host, ":")
		components.Domain = parts[0]
		port, _ := strconv.Atoi(parts[1])
		components.Port = port
	} else {
		components.Domain = host
		// 设置默认端口
		if u.Scheme == "http" {
			components.Port = 80
		} else if u.Scheme == "https" {
			components.Port = 443
		}
	}

	return components, nil
}

// func Test() {
// 	// 示例用法
// 	urls := []string{
// 		"https://www.example.com:8080/path?query=123#fragment",
// 		"http://example.com/path",
// 		"www.google.com",
// 		"//cdn.example.com:8000",
// 		"https://localhost",
// 	}

// 	for _, u := range urls {
// 		fmt.Printf("Parsing URL: %s\n", u)
// 		components, err := ParseURL(u)
// 		if err != nil {
// 			fmt.Printf("Error: %v\n", err)
// 			continue
// 		}

// 		fmt.Printf("Scheme: %s\n", components.Scheme)
// 		fmt.Printf("Domain: %s\n", components.Domain)
// 		fmt.Printf("Port: %s\n", components.Port)
// 		fmt.Printf("Path: %s\n", components.Path)
// 		fmt.Printf("Query: %s\n", components.Query)
// 		fmt.Printf("Fragment: %s\n", components.Fragment)
// 		fmt.Printf("IsHTTPS: %v\n", components.IsHTTPS)
// 		fmt.Println("-------------------")
// 	}
// }
